package com.runrunfast.fxj.config.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.runrunfast.fxj.entity.SysResources;
import com.runrunfast.fxj.entity.SysRole;
import com.runrunfast.fxj.entity.SysUser;
import com.runrunfast.fxj.enums.UserStatusEnum;
import com.runrunfast.fxj.service.ISysResourcesService;
import com.runrunfast.fxj.service.ISysRoleService;
import com.runrunfast.fxj.service.ISysUserService;
import com.runrunfast.fxj.utils.ShiroKit;
import io.swagger.annotations.ApiModelProperty;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author: 陈胤训
 * @create: 2019-03-13 14:01
 **/
public class ShiroRealm  extends AuthorizingRealm {

    @Autowired
    private ISysUserService  sysUserService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysResourcesService resourcesService;

    /**
     * 授权 提供账户信息返回认证信息（用户的角色信息集合）
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        SysUser user = ShiroKit.getUser();
        Integer userId = user.getSysUserId();

        // 赋予角色
        List<SysRole> roleList = roleService.listRolesByUserId(userId);
        for (SysRole role : roleList) {
            info.addRole(role.getRoleName());
        }
        //TODO 细密度控制还没实现
        // 赋予权限
        List<SysResources> resourcesList = resourcesService.listByUserId(userId);
        if (!CollectionUtils.isEmpty(resourcesList)) {
            for (SysResources resources : resourcesList) {
                String permission = resources.getPermission();
                System.out.println(resources.getResourcesName() + "   " + permission);
                if (!StringUtils.isEmpty(permission)) {
                    info.addStringPermission(permission);
                }
            }
        }
        return info;
    }

    /**
     * 认证登录
     * 权限认证，为当前登录的Subject授予角色和权限（角色的权限信息集合）
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户的输入的账号.
        String phone = (String) token.getPrincipal();
        SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().eq("phone",phone));
        if (user == null) {
            throw new UnknownAccountException("账号不存在！");
        }
        if (user.getStatus() != null && UserStatusEnum.DISABLE.getCode().equals(user.getStatus())) {
            throw new LockedAccountException("帐号已被锁定，禁止登录！");
        }
        // principal参数使用用户Id，方便动态刷新用户权限
        return new SimpleAuthenticationInfo(
                user,
                user.getPassword(),
                ByteSource.Util.bytes(phone),
                getName()
        );
    }


}
